#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string>
#include <cstring>

class UdpServer
{
public:
    UdpServer() : _port(8080),
                  _isrunning(false),
                  _sockfd(-1)
    {
        memset(&_addr, 0, sizeof(_addr));
    }
    ~UdpServer()
    {
        if (_sockfd >= 0)
        {
            close(_sockfd);
        }
    }

    void Start()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "socker error" << std::endl;
            return;
        }

        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = INADDR_ANY;

        int BindSuccess = bind(_sockfd, (const sockaddr *)&_addr, sizeof(_addr));
        if (BindSuccess < 0)
        {
            std::cerr << "bind error" << std::endl;
            close(_sockfd);
            _sockfd = -1;
            return;
        }

        _isrunning = true;
    }

    void stop()
    {
        _isrunning = false;
    }

    bool Recv(std::string &msg, std::string &ip, uint16_t &port)
    {
        char buf[1024];
        socklen_t len = sizeof(_addr);
        ssize_t size = recvfrom(_sockfd, buf, sizeof(buf), 0, (sockaddr *)&_addr, &len);
        if (size < 0)
        {
            std::cerr << "recvfrom error" << std::endl;
            return false;
        }
        msg = std::string(buf, size);
        ip = inet_ntoa(_addr.sin_addr);
        port = ntohs(_addr.sin_port);
        return true;
    }

    bool Send(std::string &msg, const std::string &ip, uint16_t port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        peer.sin_addr.s_addr = inet_addr(ip.c_str());
        if(inet_pton(AF_INET,ip.c_str(),&peer.sin_addr) <= 0)
        {
            std::cerr << "inet_pton error" << std::endl;
            return false;
        }
        ssize_t size = sendto(_sockfd, msg.c_str(), msg.size(), 0, (sockaddr *)&peer, sizeof(peer));
        if (size < 0)
        {
            std::cerr << "sendto error" << std::endl;
            return false;
        }
        return true;
    }

private:
    struct sockaddr_in _addr;
    int _sockfd;
    int _port;
    bool _isrunning;
};